package com.huika.renrench.control.my.account;

import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.encrypt.MD5Security;
import com.huika.lib.validation.EditTextValidator;
import com.huika.lib.validation.ValidationModel;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.Constant;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.login.validations.PassWordValidation;
import com.huika.renrench.control.login.validations.PayPassWordValidation;
import com.huika.renrench.control.login.validations.VerifyNumberValidation;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.support.bean.PayPwdVerfyBean;
import com.huika.renrench.support.bean.UserModel;
import com.huika.renrench.utils.PhoneUtil;
import com.huika.renrench.view.TitleBarHelper;
import com.huika.renrench.view.clearedit.ClearableEditText;

/**
 * @author chenyuan
 * @date：2015年6月2,下午2:15:30
 * @describe:设置支付密码activity
 */
public class SetPayPwdActivity extends BaseAct implements ErrorListener {

	private ClearableEditText etNPwd;
	private ClearableEditText etCPwd;
	private ClearableEditText etVerfy;
	private TextView btnVerfy;

	private EditTextValidator editTextValidator;
	private EditTextValidator phoneValidator;
	private LinearLayout first_enter_no_pwdLoy;

	private String phone;
	private int isSetPayPwd;// ：是否设置交易密码（0未设置1.已设置）
	private String account;
	private TextView tv_phone;

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_set_pay_pwd);
	}

	@Override
	protected void initData() {
		UserModel userModel = GlobalApp.userModel;
		phone = userModel.getPhone();
		isSetPayPwd = userModel.getIsSetPayPwd();
		account = userModel.getAccount();
	}

	@Override
	protected void initWidget() {
		TitleBarHelper titleBarHelper = new TitleBarHelper(this, -1);
		titleBarHelper.setLeftMsg(R.string.left_back);
		tv_phone = (TextView) findViewById(R.id.tv_phone);
		findViewById(R.id.btn_confirm).setOnClickListener(this);
		first_enter_no_pwdLoy = (LinearLayout) findViewById(R.id.first_enter_no_pwdLoy);
		isSetPwd(isSetPayPwd);
		etNPwd = (ClearableEditText) findViewById(R.id.et_pwd_asn);
		etCPwd = (ClearableEditText) findViewById(R.id.et_conpwd_asn);
		etVerfy = (ClearableEditText) findViewById(R.id.et_securit_code);
		btnVerfy = (TextView) findViewById(R.id.tv_get_code);
		etNPwd.addTextChangedListener(new MyPassWordWatcher(etNPwd));
		etCPwd.addTextChangedListener(new MyPassWordWatcher(etCPwd));
		btnVerfy.setOnClickListener(this);
		setVerfyEt(false);

		if (isSetPayPwd == 0) {
			editTextValidator = new EditTextValidator(this).add(new ValidationModel(etNPwd, new PayPassWordValidation())).execute();
			titleBarHelper.setTitleMsg("设置交易密码");
		} else {
			editTextValidator = new EditTextValidator(this).add(new ValidationModel(etVerfy, new VerifyNumberValidation()))
					.add(new ValidationModel(etNPwd, new PayPassWordValidation())).execute();
			titleBarHelper.setTitleMsg("修改交易密码");
		}
		tv_phone.setText(PhoneUtil.TelPhoneStr(phone));

	}

	/** 用登录返回的isSetPayPwd来判断 */
	private void isSetPwd(int flag) {
		if (flag == 0) {
			first_enter_no_pwdLoy.setVisibility(View.GONE);
		} else {
			first_enter_no_pwdLoy.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.btn_confirm:
			modifyPwdNet();
			break;
		case R.id.tv_get_code:
			verfyNet();
			break;

		default:
			break;
		}
	}

	private void verfyNet() {
		showLoadingDialog("");
		FormResultRequest<PayPwdVerfyBean> request = new FormResultRequest<PayPwdVerfyBean>(UrlConstants.GETFINDPAYPASSWORDSMSCODE, codeListener, this,
				new TypeToken<RequestResult<PayPwdVerfyBean>>() {
				}.getType());
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putStringTypeParam("phone", phone);
		ajaxParams.putStringTypeParam("account", account);
		ajaxParams.putStringTypeParam("ip", GlobalApp.ip);
		ajaxParams.putStringTypeParam("mac", GlobalApp.mac);
		ajaxParams.putStringTypeParam("dev", Constant.DEV);
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}

	private void modifyPwdNet() {
		if (editTextValidator.validate()) {
			String npwStr = getInputStr(etNPwd);
			if (npwStr == null || TextUtils.isEmpty(npwStr)) {
				showToastMsg("请输入交易密码");
				return;
			}
			String cpwStr = getInputStr(etCPwd);
			if (cpwStr == null || TextUtils.isEmpty(cpwStr)) {
				showToastMsg("请输入确认密码");
				return;
			}
			if (!npwStr.equals(cpwStr)) {
				showToastMsg("交易密码两次输入不一致，请重新输!");
				return;
			}

			showLoadingDialog("");
			FormResultRequest<String> request = new FormResultRequest<String>(UrlConstants.SETOEDITPAYPWD, setListener, errorListener, new TypeToken<RequestResult<String>>() {
			}.getType());
			JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
			ajaxParams.putStringTypeParam("account", account);
			ajaxParams.putStringTypeParam("password", MD5Security.getMd5_32_UP(npwStr));
			if (isSetPayPwd == 1) {
				ajaxParams.putStringTypeParam("validateCode", getInputStr(etVerfy));
				ajaxParams.putStringTypeParam("ip", GlobalApp.ip);
				ajaxParams.putStringTypeParam("mac", GlobalApp.mac);
				ajaxParams.putStringTypeParam("dev", Constant.DEV);
			}
			request.setRequestParams(ajaxParams);
			executeRequest(request);
		}
	}

	private Listener<RequestResult<PayPwdVerfyBean>> codeListener = new Listener<RequestResult<PayPwdVerfyBean>>() {
		@Override
		public void onResponse(RequestResult<PayPwdVerfyBean> arg0) {
			dismissLoadingDialog();
			showToastMsg(arg0.msg);
			btnVerfy.setClickable(false);
			setVerfyEt(true);
			new CountDownTimer(120000, 1000) {
				public void onTick(long millisUntilFinished) {
					btnVerfy.setTextColor(getResources().getColor(R.color.color_969696));
					btnVerfy.setText(String.format("%s秒", String.valueOf(millisUntilFinished / 1000)));
				}

				public void onFinish() {
					btnVerfy.setTextColor(getResources().getColor(R.color.color_38bdee));
					btnVerfy.setText("获取验证码");
					btnVerfy.setClickable(true);
				}
			}.start();
		}
	};

	private Listener<RequestResult<String>> setListener = new Listener<RequestResult<String>>() {
		@Override
		public void onResponse(RequestResult<String> arg0) {
			dismissLoadingDialog();
			showToastMsg(arg0.msg);
			if (arg0.flag == 1) {
				if (isSetPayPwd == 0) {
					GlobalApp.userModel.setIsSetPayPwd(1);
				}
				aty.finish();
			}
		}
	};

	ErrorListener errorListener = new ErrorListener() {

		@Override
		public void onErrorResponse(VolleyError arg0) {
			// TODO Auto-generated method stub
			showToastMsg(arg0 + "");
		}
	};

	class MyPassWordWatcher implements TextWatcher {
		private EditText editText;
		private String tempStr;

		public MyPassWordWatcher(EditText editText) {
			this.editText = editText;
		}

		@Override
		public void afterTextChanged(Editable s) {
			if (tempStr.indexOf(" ") != -1) {
				editText.setText(tempStr.trim());
				editText.setSelection(tempStr.length());
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if (s.toString().equals(" ")) {
				editText.setText("");
			} else {
				tempStr = s.toString();
			}
		}

	}

	private void setVerfyEt(boolean isShow) {
		if (isShow) {
			etVerfy.setEnabled(true);
		} else {
			etVerfy.setEnabled(false);
		}
	}

}
